package inputter;

import java.sql.Connection;
import java.sql.PreparedStatement;
import java.sql.ResultSet;
import java.util.ArrayList;
import java.util.HashSet;
import java.util.Iterator;

import org.slf4j.Logger;

import common.Log;

import main.run.MainThread;
import model.CreateConnection;
import model.Student;

public class Inputter extends Thread{
	
	private HashSet<Student> setStudent = new HashSet<Student>();
	private ArrayList<Student> lstTmp = new ArrayList<>();
	private Logger logInfo = Log.logInfo();
	private Logger logErr = Log.logErr();
//	private static int id = 0;
	//private Connection con;
	
	@Override
	public void run() {
		try {
			while(true) {
				getData();
//				getData2();
				sendData();
			}
		} catch (Exception e) {
			e.printStackTrace();
			logErr.error(e.toString());
		}
		super.run();
	}
	
	private void getData() throws Exception{
		Connection con = null;
		con = CreateConnection.getConnetion();
		String sql = "select p_student_id from p_student where isused = 'N' and rownum <= 2000";
		PreparedStatement ps = null;
		ResultSet rs = null;
		try {
			ps = con.prepareStatement(sql);
			rs = ps.executeQuery();
			
			while (rs.next()) {
				Integer p_Student_ID = rs.getInt(1);
//				System.out.println("==>" +p_Student_ID);
				Student student = new Student(p_Student_ID);
				setStudent.add(student);
			}
		} catch (Exception e) {
			e.printStackTrace();
			logErr.error(e.toString());
		} finally {
			if (rs != null) {
				rs.close();	
			}
			if (ps != null) {
				ps.close();
			}
			con.close();
		}
	}
	
//	private void getData2(){
//		Student student;
//		String firstName = "firstName";
//		String lastName = "lastName";
//		BigDecimal math = BigDecimal.ONE;
//		BigDecimal phys = BigDecimal.ONE;
//		BigDecimal chem = BigDecimal.ONE;
//		for (int i = 0; i < 2000; i++) {
//			student = new Student(id++, firstName, lastName, math, phys, chem, false);
//			setStudent.add(student);
//		}
//	}
	
	private boolean checkQueue(){
		if (MainThread.qInput.size() > 10000) {
			return false;
		}
		return true;
	}
	
	private void sendData() throws Exception{
		boolean isWait = false;
		synchronized (MainThread.qInput) {
			Iterator<Student> ite = setStudent.iterator();
			while(ite.hasNext()){
					if (!checkQueue()) {
						isWait = true;
						break;
					}
					Student student = ite.next();
					MainThread.qInput.add(student);
					student.setIsUsed(true);
					student.save();
					lstTmp.add(student);
				}
			for (int i = 0; i < lstTmp.size(); i++) {
				Student student = lstTmp.get(i);
				logInfo.info(student.toString());
				setStudent.remove(student);
			}
			if (isWait) {
				MainThread.qInput.wait(1000);
			}
		}
	}
	
}
